//
//  RegisterFirstView.swift
//  ezyform
//
//  Created by MoennigQ on 8/9/20.
//  Copyright © 2020 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import RxRelay
import IQKeyboardManagerSwift
class RegisterFirstView: GreenNaviBarView {
    lazy var disposeBag = DisposeBag()
    weak var model: RegisterModel!
    //
    let scrollView = DIYScrollView()
    let toolBar = UIToolbar()
    //
    let roleTipLabel = ContentLabel(R.font.interRegular(size: 11),hexStr: "#ED3E3EFF")
    let installerCheckBtn = CheckboxButton(title: R.string.localizable.installer())
    let designerCheckBtn = CheckboxButton(title: R.string.localizable.designer())
    let electricianCheckBtn = CheckboxButton(title: R.string.localizable.electrician())
    //title
    let accreditationNumberTitle = BaseLabel()
    let eletricianLicenseTitle = BaseLabel()
    //textfield
    let accreditationNumberTextField = TextFieldWithRequiredView()
    let electricianLicenseTextField = TextFieldWithRequiredView()
    let firstNameTextField = TextFieldWithRequiredView(.username)
    let lastNameTextField = TextFieldWithRequiredView(.username)
    let phoneTextField = TextFieldWithRequiredView(.phone)
    let emailTextField = TextFieldWithRequiredView(.email)
    let pwdTextField = TextFieldWithRequiredView(.password)
    let confirmPwdTextField = TextFieldWithRequiredView(.password)
    
    //continue
    let continueBtn = OperationButton(R.string.localizable.continue())
    //
    let titleFont: UIFont = R.font.interMedium(size: 14)!
    let titleColor: UIColor = UIColor(hexStr: "#292D32")
    override func setUpView() {
        self.backgroundColor = .white
        scrollView.backgroundColor = .white
        scrollView.drawCorner(byRoundingCorners: [.topRight,.topLeft])
        self.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.top.equalTo(topBackView.snp.bottom).offset(-20)
            make.left.right.equalTo(self)
            make.height.greaterThanOrEqualTo(0)
        }
        
        let backView = IQPreviousNextView()
        backView.backgroundColor = .white
        scrollView.addSubview(backView)
        backView.snp.makeConstraints { (make) in
            make.top.bottom.equalTo(scrollView)
            make.left.right.equalTo(self)
            make.height.greaterThanOrEqualTo(0)
        }
        //Role title
        let roleTitle = TitleLabelWithRequired(R.string.localizable.role())
        backView.addSubview(roleTitle)
        roleTitle.snp.makeConstraints { (make) in
            make.top.equalTo(20)
            make.left.equalTo(16)
        }
        //installer, designer, electician check
        let checkBtnWidth: CGFloat = (APPConfig.WidthForPortrait - 16 * 2) / 3
        
        //installer check btn
        backView.addSubview(installerCheckBtn)
        installerCheckBtn.snp.makeConstraints { (make) in
            make.top.equalTo(roleTitle.snp.bottom).offset(15)
            make.left.equalTo(roleTitle)
            make.height.equalTo(40)
            make.width.greaterThanOrEqualTo(0)
        }
        //designer
        backView.addSubview(designerCheckBtn)
        designerCheckBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(installerCheckBtn)
            if APPConfig.WidthForPortrait == 320{
                make.left.equalTo(installerCheckBtn.snp.right)
            }else{
                make.left.equalTo(checkBtnWidth + 20)
            }
            
            make.height.equalTo(installerCheckBtn)
            make.width.greaterThanOrEqualTo(0)
        }
        //electrician
        backView.addSubview(electricianCheckBtn)
        electricianCheckBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(installerCheckBtn)
            if APPConfig.WidthForPortrait == 320{
                make.left.equalTo(designerCheckBtn.snp.right)
            }else{
                make.left.equalTo(checkBtnWidth * 2 + 20)
            }
            
            make.height.equalTo(installerCheckBtn)
            make.width.greaterThanOrEqualTo(0)
        }
        //role tip label
        self.addSubview(roleTipLabel)
        roleTipLabel.snp.makeConstraints { (make) in
            make.top.equalTo(installerCheckBtn.snp.bottom)
            make.left.equalTo(roleTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        
        /// change
        var showTitleString = "Accreditation(SAA) Number"
        if XpTools.isGreaterThanOverTime() == true { // 失效
            showTitleString = "Standards Association of Australia number"
        }
                
            
        
        //Accreditation  Number title
        accreditationNumberTitle.attributedText = Tool().getFormatTitle(showTitleString,textFont: titleFont, textColor: titleColor)
        backView.addSubview(accreditationNumberTitle)
        accreditationNumberTitle.snp.makeConstraints { (make) in
            make.top.equalTo(roleTipLabel.snp.bottom).offset(20)
            make.left.equalTo(roleTitle)
            make.width.height.greaterThanOrEqualTo(0)
        }
        //Accreditation  Number
        backView.addSubview(accreditationNumberTextField)
        accreditationNumberTextField.snp.makeConstraints { (make) in
            make.top.equalTo(accreditationNumberTitle.snp.bottom).offset(12)
            make.left.equalTo(roleTitle)
            make.right.equalTo(-16)
            make.height.greaterThanOrEqualTo(0)
        }
        //Electrician Licenses title
        eletricianLicenseTitle.attributedText = Tool().getFormatTitle(R.string.localizable.electricianLicenses(),textFont: titleFont, textColor: titleColor)
        backView.addSubview(eletricianLicenseTitle)
        eletricianLicenseTitle.snp.makeConstraints { (make) in
            make.top.equalTo(accreditationNumberTextField.snp.bottom).offset(20)
            make.left.equalTo(roleTitle)
            make.width.height.greaterThanOrEqualTo(0)
        }
        //Electrician Licenses
        backView.addSubview(electricianLicenseTextField)
        electricianLicenseTextField.snp.makeConstraints { (make) in
            make.top.equalTo(eletricianLicenseTitle.snp.bottom).offset(12)
            make.left.right.equalTo(accreditationNumberTextField)
            make.height.greaterThanOrEqualTo(0)
        }
        //first name title
        let firstNameTitle = BaseLabel()
        firstNameTitle.attributedText = Tool().getFormatTitle(R.string.localizable.firstName(), subStr: "*",textFont: titleFont, textColor: titleColor)
        backView.addSubview(firstNameTitle)
        firstNameTitle.snp.makeConstraints { (make) in
            make.top.equalTo(electricianLicenseTextField.snp.bottom).offset(20)
            make.left.equalTo(roleTitle)
            make.width.height.greaterThanOrEqualTo(0)
        }
        //firstName
        backView.addSubview(firstNameTextField)
        firstNameTextField.snp.makeConstraints { (make) in
            make.top.equalTo(firstNameTitle.snp.bottom).offset(12)
            make.left.right.equalTo(accreditationNumberTextField)
            make.height.greaterThanOrEqualTo(0)
        }
        //last name title
        let lastNameTitle = BaseLabel()
        lastNameTitle.attributedText = Tool().getFormatTitle(R.string.localizable.lastName(), subStr: "*",textFont: titleFont, textColor: titleColor)
        backView.addSubview(lastNameTitle)
        lastNameTitle.snp.makeConstraints { (make) in
            make.top.equalTo(firstNameTextField.snp.bottom).offset(20)
            make.left.equalTo(roleTitle)
            make.width.height.greaterThanOrEqualTo(0)
        }
        //last Name
        backView.addSubview(lastNameTextField)
        lastNameTextField.snp.makeConstraints { (make) in
            make.top.equalTo(lastNameTitle.snp.bottom).offset(12)
            make.left.right.equalTo(accreditationNumberTextField)
            make.height.greaterThanOrEqualTo(0)
        }
        //phone title
        let phoneTitle = BaseLabel()
        phoneTitle.attributedText = Tool().getFormatTitle(R.string.localizable.phone(), subStr: "*",textFont: titleFont, textColor: titleColor)
        backView.addSubview(phoneTitle)
        phoneTitle.snp.makeConstraints { (make) in
            make.top.equalTo(lastNameTextField.snp.bottom).offset(20)
            make.left.equalTo(roleTitle)
            make.width.height.greaterThanOrEqualTo(0)
        }
        //phone
        backView.addSubview(phoneTextField)
        phoneTextField.snp.makeConstraints { (make) in
            make.top.equalTo(phoneTitle.snp.bottom).offset(12)
            make.left.right.equalTo(accreditationNumberTextField)
            make.height.greaterThanOrEqualTo(0)
        }
        //email title
        let emailTitle = BaseLabel()
        emailTitle.attributedText = Tool().getFormatTitle(R.string.localizable.email(), subStr: "*",textFont: titleFont, textColor: titleColor)
        backView.addSubview(emailTitle)
        emailTitle.snp.makeConstraints { (make) in
            make.top.equalTo(phoneTextField.snp.bottom).offset(20)
            make.left.equalTo(roleTitle)
            make.width.height.greaterThanOrEqualTo(0)
        }
        //email
        backView.addSubview(emailTextField)
        emailTextField.snp.makeConstraints { (make) in
            make.top.equalTo(emailTitle.snp.bottom).offset(12)
            make.left.right.equalTo(accreditationNumberTextField)
            make.height.greaterThanOrEqualTo(0)
        }
        //pwd title
        let pwdTitle = BaseLabel()
        pwdTitle.attributedText = Tool().getFormatTitle(R.string.localizable.password(), subStr: "*",textFont: titleFont, textColor: titleColor)
        backView.addSubview(pwdTitle)
        pwdTitle.snp.makeConstraints { (make) in
            make.top.equalTo(emailTextField.snp.bottom).offset(20)
            make.left.equalTo(roleTitle)
            make.width.height.greaterThanOrEqualTo(0)
        }
        //pwd
        pwdTextField.textField.isSecureTextEntry = true
        backView.addSubview(pwdTextField)
        pwdTextField.snp.makeConstraints { (make) in
            make.top.equalTo(pwdTitle.snp.bottom).offset(12)
            make.left.right.equalTo(accreditationNumberTextField)
            make.height.greaterThanOrEqualTo(0)
        }
        //confirm pwd title
        let confirdPwdTitle = BaseLabel()
        confirdPwdTitle.attributedText = Tool().getFormatTitle(R.string.localizable.passwordConfirmation(), subStr: "*",textFont: titleFont, textColor: titleColor)
        backView.addSubview(confirdPwdTitle)
        confirdPwdTitle.snp.makeConstraints { (make) in
            make.top.equalTo(pwdTextField.snp.bottom).offset(20)
            make.left.equalTo(roleTitle)
            make.width.height.greaterThanOrEqualTo(0)
        }
        //confirdPwd
        confirmPwdTextField.textField.isSecureTextEntry = true
        backView.addSubview(confirmPwdTextField)
        confirmPwdTextField.snp.makeConstraints { (make) in
            make.top.equalTo(confirdPwdTitle.snp.bottom).offset(12)
            make.left.right.equalTo(accreditationNumberTextField)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalTo(-20)
        }
        //continue btn
        self.addSubview(continueBtn)
        continueBtn.snp.makeConstraints { (make) in
            make.top.equalTo(scrollView.snp.bottom)
            make.left.right.equalTo(accreditationNumberTextField)
            make.height.equalTo(OperationButton.height)
            make.bottom.equalTo(OperationButton.bottomMargin)
            
        }
        //没选择角色前，设置为非必填项
        self.accreditationNumberTextField.changeCheckFlag(false)
        self.electricianLicenseTextField.changeCheckFlag(false)
        //绑定
        self.checkEverythingValid()
    }
    //MARK: - 必填项数据绑定控制continue btn是否可用
    private func checkEverythingValid(){
        //role至少选一个
        let installerValid = self.installerCheckBtn.rx.observe(Int.self, "tag").map({$0 == 1}).share(replay: 1)
        let designerValid = self.designerCheckBtn.rx.observe(Int.self, "tag").map({$0 == 1}).share(replay: 1)
        let electricianValid = self.electricianCheckBtn.rx.observe(Int.self, "tag").map({$0 == 1}).share(replay: 1)
        let roleValid = Observable.combineLatest(
            installerValid,
            designerValid,
            electricianValid
        ) { $0 || $1 || $2} // 取用户名和密码同时有效
        .share(replay: 1)
        //other
        let validAccreditationNumber = self.accreditationNumberTextField.validStatus.map({$0 == .valid}).share(replay: 1)
        let validElectricianLicense = self.electricianLicenseTextField.validStatus.map({$0 == .valid}).share(replay: 1)
        let validFirstName = self.firstNameTextField.validStatus.map({$0 == .valid}).share(replay: 1)
        let validLastName = self.lastNameTextField.validStatus.map({$0 == .valid}).share(replay: 1)
        let validPhone = self.phoneTextField.validStatus.map({$0 == .valid}).share(replay: 1)
        let validEmail = self.emailTextField.validStatus.map({$0 == .valid}).share(replay: 1)
        let validPwd = self.pwdTextField.validStatus.map({$0 == .valid}).share(replay: 1)
        let validConfirmPwd = self.confirmPwdTextField.validStatus.map({$0 == .valid}).share(replay: 1)
        //
        let otherValid = Observable.combineLatest(
            validAccreditationNumber,
            validElectricianLicense,
            validFirstName,
            validLastName,
            validPhone,
            validEmail,
            validPwd,
            validConfirmPwd
          ) { $0 && $1 && $2 && $3 && $4 && $5 && $6 && $7 } // 取用户名和密码同时有效
          .share(replay: 1)
        //Observable.combineLatest只能传8个参数，所以要分成两段处理
        let everythingValid = Observable.combineLatest(
            roleValid,
            otherValid
          ) { $0 && $1} // 取用户名和密码同时有效
          .share(replay: 1)
        
        everythingValid.subscribe { [weak self] (valid) in
            guard let strongSelf = self else {return}
            if valid {
                strongSelf.continueBtn.enableBtn()
            }else{
                strongSelf.continueBtn.disableBtn()
            }
        }.disposed(by: self.disposeBag)
    }
    //MARK: -将编辑数据和model绑定
    func dataBinding(_ model: RegisterModel){
        self.model = model
        //选择installer
        self.installerCheckBtn.clickClosure = {[weak self] (tag)in
            guard let strongSelf = self else {return }
            strongSelf.model.installer = (tag == 1 ? true : false)
            strongSelf.checkIfInstaller()
        }
        //选择designer
        self.designerCheckBtn.clickClosure = {[weak self] (tag)in
            guard let strongSelf = self else {return }
            strongSelf.model.designer = (tag == 1 ? true : false)
            strongSelf.checkIfDesigner()
        }
        //选择electrician
        self.electricianCheckBtn.clickClosure = {[weak self] (tag)in
            guard let strongSelf = self else {return }
            strongSelf.model.electrician = (tag == 1 ? true : false)
            strongSelf.checkIfElectrician()
        }
        //accreditationNumber
        self.accreditationNumberTextField.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.model.accredited_number = data
            strongSelf.checkAccreditedNumber()
        }
        //electricianLicense
        self.electricianLicenseTextField.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.model.electrician_licenses = data
        }
        //first_name
        self.firstNameTextField.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.model.first_name = data
            strongSelf.checkAccreditedNumberAndName()
        }
        //last_name
        self.lastNameTextField.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.model.last_name = data
            strongSelf.checkAccreditedNumberAndName()
        }
        //phone
        self.phoneTextField.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.model.phone = data
        }
        //email
        self.emailTextField.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.model.email = data
            if strongSelf.emailTextField.validStatus.value == .valid {//通过了email的非空，email格式校验规则
                strongSelf.checkEmailWhenRegister()
            }
        }
        //password
        self.pwdTextField.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.model.password = data
            strongSelf.checkIfPwdAndConfirmPwdInconsistent()
        }
        //password_confirmation
        self.confirmPwdTextField.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.model.password_confirmation = data
            strongSelf.checkIfPwdAndConfirmPwdInconsistent()
        }
    }
    //MARK: - 检查密码是否匹配
    private func checkIfPwdAndConfirmPwdInconsistent(){
        if self.model.password_confirmation != self.model.password && self.model.password_confirmation != "" && self.model.password != ""{
            self.confirmPwdTextField.showInvalidMsg(R.string.localizable.changePasswordPasswordsInconsistent())
        }
    }
    //MARK: - 调用API检查Accreditation Number在我们系统中是否已经注册
    func checkAccreditedNumber(){
        if self.model.accredited_number == ""{
            //不为空才隐藏校验的提示信息，因为为空要提示this is required
            if self.model.first_name != ""{
                self.firstNameTextField.hideInvalidMsg()
            }
            if self.model.last_name != ""{
                self.lastNameTextField.hideInvalidMsg()
            }
        }else{
            let vm = RegisterService()
            vm.setBlockAfterNetwork({ [weak self](result , _) -> Void in
                guard let strongSelf = self else {return}
                strongSelf.accreditationNumberTextField.hideInvalidMsg()
                strongSelf.checkAccreditedNumberAndName()
            }) {[weak self](code,msg) -> Void in
                guard let strongSelf = self else {return}
                strongSelf.accreditationNumberTextField.showInvalidMsg(msg)
            }
            vm.checkAccreditedNumberWhenRegister(self.model.accredited_number)
        }
        
    }
    //MARK: - 校验Email是否已经注册过
    private func checkEmailWhenRegister(){
        let vm = RegisterService()
        vm.setBlockAfterNetwork({  [weak self](result , _) -> Void in
            guard let strongSelf = self else {return}
            strongSelf.emailTextField.hideInvalidMsg()
        }) {[weak self](code,msg) -> Void in
            guard let strongSelf = self else {return}
            strongSelf.emailTextField.showInvalidMsg(msg)
        }
        vm.checkEmailWhenRegister(self.model.email)
    }
    //MARK: - 提交时要校验AccreditedNumber ， name是否匹配
    fileprivate func checkAccreditedNumberAndName(){
        guard self.model.accredited_number != "" && self.model.first_name  != "" && self.model.last_name  != "" else{
            //不为空才隐藏校验的提示信息，因为为空要提示this is required
            if self.model.first_name != ""{
                self.firstNameTextField.hideInvalidMsg()
            }
            if self.model.last_name != ""{
                self.lastNameTextField.hideInvalidMsg()
            }
            if self.model.accredited_number != ""{
                self.accreditationNumberTextField.hideInvalidMsg()
            }
            return
        }
        let vm = RegisterService()
        vm.setBlockAfterNetwork({[weak self] (result , _) -> Void in
            guard let strongSelf = self else { return  }
            strongSelf.accreditationNumberTextField.hideInvalidMsg()
            strongSelf.firstNameTextField.hideInvalidMsg()
            strongSelf.lastNameTextField.hideInvalidMsg()
        }) {[weak self](code,msg) -> Void in
            guard let strongSelf = self else {return}
            strongSelf.accreditationNumberTextField.showInvalidMsg(msg)
            strongSelf.firstNameTextField.showInvalidMsg(msg)
            strongSelf.lastNameTextField.showInvalidMsg(msg)
            
        }
        vm.checkAccreditedNumberAndNameWhenRegisterContinue(self.model)
    }
    //MARK: - 选择installer角色
    private func checkIfInstaller(){
        var starStr: String = ""
        //installer or designer 必填accredition number
        if self.installerCheckBtn.tag == 1 || self.designerCheckBtn.tag == 1 {
            starStr = "*"
            self.accreditationNumberTextField.changeCheckFlag(true)
        }else{
            self.accreditationNumberTextField.changeCheckFlag(false)
        }
        self.accreditationNumberTitle.attributedText = Tool().getFormatTitle(R.string.localizable.accreditationNumber(), subStr: starStr,textFont: titleFont, textColor: titleColor)
        //
        if self.installerCheckBtn.tag == 1 || self.designerCheckBtn.tag == 1 || self.electricianCheckBtn.tag == 1 {
            self.roleTipLabel.text = ""
        }else{
            self.roleTipLabel.text = R.string.localizable.thisFieldIsRequird()
        }
    }
    //MARK: - 选择Designer角色
    private func checkIfDesigner(){
        var starStr: String = ""
        //installer or designer 必填accredition number
        if self.installerCheckBtn.tag == 1 || self.designerCheckBtn.tag == 1 {
            starStr = "*"
            self.accreditationNumberTextField.changeCheckFlag(true)
        }else{
            self.accreditationNumberTextField.changeCheckFlag(false)
        }
        self.accreditationNumberTitle.attributedText = Tool().getFormatTitle(R.string.localizable.accreditationNumber(), subStr: starStr,textFont: titleFont, textColor: titleColor)
        //
        if self.installerCheckBtn.tag == 1 || self.designerCheckBtn.tag == 1 || self.electricianCheckBtn.tag == 1 {
            self.roleTipLabel.text = ""
        }else{
            self.roleTipLabel.text = R.string.localizable.thisFieldIsRequird()
        }
    }
    //MARK: - 选择Electrician角色
    private func checkIfElectrician(){
        var starStr: String = ""
        //电工 必填electrician license
        if self.electricianCheckBtn.tag == 1  {
            starStr = "*"
            self.electricianLicenseTextField.changeCheckFlag(true)
        }else{
            self.electricianLicenseTextField.changeCheckFlag(false)
        }
        eletricianLicenseTitle.attributedText = Tool().getFormatTitle(R.string.localizable.electricianLicenses(), subStr: starStr,textFont: titleFont, textColor: titleColor)
        //
        if self.installerCheckBtn.tag == 1 || self.designerCheckBtn.tag == 1 || self.electricianCheckBtn.tag == 1 {
            self.roleTipLabel.text = ""
        }else{
            self.roleTipLabel.text = R.string.localizable.thisFieldIsRequird()
        }
    }
}
